//
//  TMNetwork.m
//  TMtravel
//
//  Created by Playboy on 17/3/10.
//  Copyright © 2017年 tmkj. All rights reserved.
//

#import "TMNetwork.h"
#import <AlipaySDK/AlipaySDK.h>

#define BASE_URL @"http://rzccq.com/api"

@interface TMNetwork ()

@end

@implementation TMNetwork

+ (TMNetwork *)manager
{
    static TMNetwork *sharedManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedManager = [[TMNetwork alloc]init];
    });
    return  sharedManager;
}

-(instancetype)init{
    self=[super init];
    if (self) {
        _manager=[AFHTTPSessionManager manager];
        _manager.operationQueue.maxConcurrentOperationCount=1;
        _manager.requestSerializer = [AFJSONRequestSerializer new];
        _manager.requestSerializer=[AFJSONRequestSerializer serializer];
        _manager.responseSerializer=[AFHTTPResponseSerializer serializer];
        _manager.requestSerializer.timeoutInterval = 30.f;
        [_manager.reachabilityManager startMonitoring];
        NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
        NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
        [_manager.requestSerializer setValue:app_Version forHTTPHeaderField:@"version"];
    }
    
    return self;
}

//字典转为Json字符串
+(NSString *)dictionaryToJson:(NSDictionary *)dic
{
    if (!dic) {
        return @"";
    }
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

+ (NSDictionary *)jsonToDictionary:(NSString *)jsonString {
    
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                         
                                                        options:NSJSONReadingMutableContainers
                         
                                                          error:&err];
    
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

+ (void)requestPostWithParam:(id)param url:(NSString *)urlString callback:(networkCompleteBlock)callback {
    NSString *token = [kUserDefaults objectForKey:@"token"];
    [[TMNetwork manager].manager.requestSerializer setValue:token forHTTPHeaderField:@"user-token"];
    NSString *url = [NSString stringWithFormat:@"%@%@",BASE_URL,urlString];

    NSLog(@"url=%@",url);
    NSLog(@"param=%@",param);
    [[TMNetwork manager].manager POST:url parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"result=%@",dic);
        TMBaseReqModel *model = [TMBaseReqModel objectWithKeyValues:dic];
        if (model.code == 401) {
            [[TMShareData shareData] pushLogin];
        }
        if (callback) {
            callback (model);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
        TMBaseReqModel *model = [[TMBaseReqModel alloc] init];
        model.message = @"连接服务器失败，请稍后再试。";
        model.code = 0;
        if (callback) {
            callback (model);
        }
    }];
    
}

+ (void)requestGetWithParam:(NSDictionary *)param url:(NSString *)urlString callback:(networkCompleteBlock)callback {
    NSString *token = [kUserDefaults objectForKey:@"token"];
    [[TMNetwork manager].manager.requestSerializer setValue:token forHTTPHeaderField:@"user-token"];
    NSString *url = [NSString stringWithFormat:@"%@%@",BASE_URL,urlString];
    
    NSLog(@"url=%@",url);
    NSLog(@"param=%@",param);
    
    [[TMNetwork manager].manager GET:url parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"result=%@",dic);
        TMBaseReqModel *model = [TMBaseReqModel objectWithKeyValues:dic];
        if (model.code == 401) {
            [[TMShareData shareData] pushLogin];
        }
        if (callback) {
            callback (model);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        TMBaseReqModel *model = [[TMBaseReqModel alloc] init];
        model.message = @"连接服务器失败，请稍后再试。";
        model.code = 0;
        if (callback) {
            callback (model);
        }
    }];
}


+ (void)requestImageWithImage:(NSData *)imageData url:(NSString *)urlString callback:(networkCompleteBlock)callback {
    NSString *url = [NSString stringWithFormat:@"%@%@",BASE_URL,urlString];
    NSLog(@"url = %@",url);
    [[TMNetwork manager].manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSString * Name = [NSString stringWithFormat:@"%@[1]", @"tmImage"];
        NSString * fileName = [NSString stringWithFormat:@"%@.jpg", Name];
        [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/jpeg"];
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"resultDic = %@",resultDic);
        TMBaseReqModel *model = [TMBaseReqModel objectWithKeyValues:resultDic];
        if (callback) {
            callback (model);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        TMBaseReqModel *model = [[TMBaseReqModel alloc] init];
        model.code = 0;
        model.message = @"连接服务器失败，请稍后再试";
        if (callback) {
            callback (model);
        }
    }];
}
+ (void)requestImageWithImageArray:(NSArray *)imageArray callback:(networkCompleteBlock)callback {
    [[TMNetwork manager].manager POST:@"http://rzccq.com/api/file/upload/list" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
//        NSString * Name = [NSString stringWithFormat:@"%@[1]", @"tmImage"];
//        NSString * fileName = [NSString stringWithFormat:@"%@.jpg", Name];
//        [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/jpeg"];
        // 上传多张图片
        for(NSInteger i = 0; i < imageArray.count; i++)
        {
            // 取出单张图片二进制数据
            NSData * imageData = imageArray[i];
            
            // 上传的参数名，在服务器端保存文件的文件夹名
            NSString * Name = [NSString stringWithFormat:@"%@[%zd]", @"file",i+1];
            
            // 上传filename
            NSString * fileName = [NSString stringWithFormat:@"%@.jpg", Name];
            
            [formData appendPartWithFileData:imageData name:Name fileName:fileName mimeType:@"image/jpeg"];
        }
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"resultDic = %@",resultDic);
        TMBaseReqModel *model = [TMBaseReqModel objectWithKeyValues:resultDic];
        if (callback) {
            callback (model);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        TMBaseReqModel *model = [[TMBaseReqModel alloc] init];
        model.code = 0;
        model.message = @"连接服务器失败，请稍后再试";
        if (callback) {
            callback (model);
        }
    }];
}

+ (void)alipayWithParam:(NSString *)param {
    // NOTE: 调用支付结果开始支付
    NSString *appScheme = @"pbhomedemo";
    [[AlipaySDK defaultService] payOrder:param fromScheme:appScheme callback:^(NSDictionary *resultDic) {
        NSLog(@"reslut = %@",resultDic);
    }];
}


- (AFNetworkReachabilityStatus)networkStatus {
    return [TMNetwork manager].manager.reachabilityManager.networkReachabilityStatus;
}
@end
